<template>
  <view class="supplier-goods-container">
    <!-- 顶部说明 -->
    <view class="header-tip">
      <uni-icons type="info" size="16" color="#1890ff"></uni-icons>
      <text class="tip-text">配置供货商可提供的商品，用于预约申请时的快速选择</text>
    </view>

    <!-- 供货商选择 -->
    <view class="supplier-selector">
      <view class="section-title">
        <uni-icons type="contact" size="20" color="#333"></uni-icons>
        <text class="title-text">选择供货商</text>
      </view>
      
      <picker 
        :value="supplierIndex" 
        :range="supplierList" 
        range-key="supplierName"
        @change="onSupplierChange"
      >
        <view class="picker-wrapper">
          <text class="picker-text">
            {{ supplierIndex >= 0 ? supplierList[supplierIndex].supplierName : '请选择供货商' }}
          </text>
          <uni-icons type="bottom" size="16" color="#999"></uni-icons>
        </view>
      </picker>
    </view>

    <!-- 商品关联配置 -->
    <view class="goods-section" v-if="goodsList.length > 0">
      <view class="section-title">
        <uni-icons type="list" size="20" color="#333"></uni-icons>
        <text class="title-text">可提供商品</text>
        <view class="title-actions" v-if="supplierIndex >= 0">
          <button class="save-btn" @click="saveRelations" :disabled="saving">
            <uni-icons type="checkmarkempty" size="14" color="#fff"></uni-icons>
            <text class="btn-text">{{ saving ? '保存中...' : '保存配置' }}</text>
          </button>
        </view>
      </view>

      <!-- 未选择供货商的提示 -->
      <view class="supplier-tip" v-if="supplierIndex < 0">
        <uni-icons type="info" size="20" color="#faad14"></uni-icons>
        <text class="tip-text">请先选择供货商，然后配置该供货商可提供的商品</text>
      </view>

      <!-- 全选/反选 -->
      <view class="select-all-section" v-if="supplierIndex >= 0">
        <view class="select-all-item" @click="toggleSelectAll">
          <view class="checkbox-wrapper">
            <view class="checkbox" :class="{ checked: allSelected }">
              <uni-icons v-if="allSelected" type="checkmarkempty" size="16" color="#fff"></uni-icons>
            </view>
          </view>
          <text class="select-text">{{ allSelected ? '取消全选' : '全选商品' }}</text>
        </view>
      </view>

      <!-- 商品列表 -->
      <view class="goods-list" v-if="supplierIndex >= 0">
        <view 
          class="goods-item" 
          v-for="(item, index) in goodsList" 
          :key="item.goodsId"
          @click="toggleGoodsSelection(index)"
        >
          <view class="checkbox-wrapper">
            <view class="checkbox" :class="{ checked: item.selected }">
              <uni-icons v-if="item.selected" type="checkmarkempty" size="16" color="#fff"></uni-icons>
            </view>
          </view>
          
          <view class="goods-info">
            <text class="goods-name">{{ item.goodsName }}</text>
            <view class="goods-details">
              <text class="goods-category">{{ getCategoryText(item.goodsCategory) }}</text>
              <text class="goods-unit">{{ item.unit || '-' }}</text>
            </view>
            <view class="goods-origin" v-if="item.originProvince || item.originCity">
              <uni-icons type="location" size="12" color="#999"></uni-icons>
              <text class="origin-text">{{ getOriginText(item) }}</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="goodsList.length === 0 && !loading">
          <image src="/static/images/empty.png" class="empty-image"></image>
          <text class="empty-text">暂无商品数据</text>
          <view class="empty-action" @click="goToAddGoods">
            <uni-icons type="plus" size="16" color="#1890ff"></uni-icons>
            <text class="empty-action-text">添加商品</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <uni-icons type="spinner-cycle" size="24" color="#1890ff"></uni-icons>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script>
import { mySupplierList } from '@/api/business/supplier.js'
import { myGoodsList } from '@/api/business/goods.js'
import { getGoodsBySupplier, updateSupplierGoodsRelation } from '@/api/system/supplierGoods.js'

export default {
  data() {
    return {
      supplierList: [],
      supplierIndex: -1,
      goodsList: [],
      selectedGoodsIds: [],
      loading: false,
      saving: false,
      categoryMap: {
        '0': '种植业',
        '1': '养殖业', 
        '2': '畜牧业'
      }
    }
  },
  computed: {
    allSelected() {
      return this.goodsList.length > 0 && this.goodsList.every(item => item.selected)
    },
    selectedSupplier() {
      return this.supplierIndex >= 0 ? this.supplierList[this.supplierIndex] : null
    }
  },
  onLoad() {
    this.loadSuppliers()
    this.loadGoods()
  },
  methods: {
    // 加载供货商列表
    async loadSuppliers() {
      try {
        const response = await mySupplierList()
        if (response.code === 200) {
          this.supplierList = response.data || []
        }
      } catch (error) {
        console.error('加载供货商列表失败:', error)
        uni.showToast({
          title: '加载供货商失败',
          icon: 'none'
        })
      }
    },

    // 加载商品列表
    async loadGoods() {
      try {
        this.loading = true
        const response = await myGoodsList()
        if (response.code === 200) {
          this.goodsList = (response.data || []).map(item => ({
            ...item,
            selected: false
          }))
        }
      } catch (error) {
        console.error('加载商品列表失败:', error)
        uni.showToast({
          title: '加载商品失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 供货商选择变化
    async onSupplierChange(e) {
      this.supplierIndex = parseInt(e.detail.value)
      if (this.supplierIndex >= 0) {
        await this.loadSupplierGoods()
      }
    },

    // 加载供货商已关联的商品
    async loadSupplierGoods() {
      if (!this.selectedSupplier) return

      try {
        this.loading = true
        const response = await getGoodsBySupplier(this.selectedSupplier.supplierId)
        if (response.code === 200) {
          const linkedGoodsIds = (response.data || []).map(item => item.goodsId)
          
          // 更新商品选中状态
          this.goodsList.forEach(item => {
            item.selected = linkedGoodsIds.includes(item.goodsId)
          })
          
          this.selectedGoodsIds = linkedGoodsIds
        }
      } catch (error) {
        console.error('加载供货商商品关联失败:', error)
        uni.showToast({
          title: '加载关联数据失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 切换商品选择状态
    toggleGoodsSelection(index) {
      if (this.supplierIndex < 0) {
        uni.showToast({
          title: '请先选择供货商',
          icon: 'none'
        })
        return
      }
      this.goodsList[index].selected = !this.goodsList[index].selected
      this.$forceUpdate()
    },

    // 全选/取消全选
    toggleSelectAll() {
      const newStatus = !this.allSelected
      this.goodsList.forEach(item => {
        item.selected = newStatus
      })
      this.$forceUpdate()
    },

    // 保存关联关系
    async saveRelations() {
      if (!this.selectedSupplier) {
        uni.showToast({
          title: '请先选择供货商',
          icon: 'none'
        })
        return
      }

      const selectedGoodsIds = this.goodsList
        .filter(item => item.selected)
        .map(item => item.goodsId)

      try {
        this.saving = true
        uni.showLoading({ title: '保存中...' })

        const response = await updateSupplierGoodsRelation({
          supplierId: this.selectedSupplier.supplierId,
          goodsIds: selectedGoodsIds
        })

        uni.hideLoading()

        if (response.code === 200) {
          this.selectedGoodsIds = selectedGoodsIds
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: response.msg || '保存失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('保存供货商商品关联失败:', error)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      } finally {
        this.saving = false
      }
    },

    // 获取分类文本
    getCategoryText(category) {
      return this.categoryMap[category] || '其他'
    },

    // 获取产地文本
    getOriginText(item) {
      const parts = []
      if (item.originProvince) parts.push(item.originProvince)
      if (item.originCity) parts.push(item.originCity)
      if (item.originDistrict) parts.push(item.originDistrict)
      return parts.join(' ')
    },

    // 跳转到添加商品页面
    goToAddGoods() {
      uni.navigateTo({
        url: '/pages/goods/add'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.supplier-goods-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

/* 顶部提示 */
.header-tip {
  background: #e6f7ff;
  border: 1rpx solid #91d5ff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;

  .tip-text {
    font-size: 28rpx;
    color: #1890ff;
    margin-left: 12rpx;
    line-height: 1.4;
  }
}

/* 供货商选择 */
.supplier-selector {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

/* 商品配置区域 */
.goods-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

/* 区块标题 */
.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;

  .title-text {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    margin-left: 12rpx;
    flex: 1;
  }

  .title-actions {
    .save-btn {
      display: flex;
      align-items: center;
      background: linear-gradient(135deg, #4CAF50, #66BB6A);
      color: white;
      border: none;
      border-radius: 30rpx;
      padding: 12rpx 24rpx;
      font-size: 26rpx;

      &:disabled {
        background: #ccc;
      }

      .btn-text {
        margin-left: 8rpx;
      }
    }
  }
}

/* 选择器样式 */
.picker-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 12rpx;
  background: #fafafa;

  .picker-text {
    font-size: 30rpx;
    color: #333;
    flex: 1;
  }
}

/* 供货商提示 */
.supplier-tip {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background: #fff7e6;
  border: 1rpx solid #ffd591;
  border-radius: 12rpx;
  margin-bottom: 20rpx;

  .tip-text {
    font-size: 28rpx;
    color: #faad14;
    margin-left: 12rpx;
    line-height: 1.4;
  }
}

/* 全选区域 */
.select-all-section {
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .select-all-item {
    display: flex;
    align-items: center;
    padding: 12rpx 0;

    .select-text {
      font-size: 30rpx;
      color: #1890ff;
      margin-left: 16rpx;
    }
  }
}

/* 商品列表 */
.goods-list {
  .goods-item {
    display: flex;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .goods-info {
      flex: 1;
      margin-left: 16rpx;

      .goods-name {
        font-size: 32rpx;
        color: #333;
        font-weight: 500;
        margin-bottom: 8rpx;
        display: block;
      }

      .goods-details {
        display: flex;
        align-items: center;
        margin-bottom: 8rpx;

        .goods-category {
          font-size: 26rpx;
          color: #666;
          margin-right: 20rpx;
        }

        .goods-unit {
          font-size: 26rpx;
          color: #999;
        }
      }

      .goods-origin {
        display: flex;
        align-items: center;

        .origin-text {
          font-size: 24rpx;
          color: #999;
          margin-left: 6rpx;
        }
      }
    }
  }
}

/* 复选框样式 */
.checkbox-wrapper {
  .checkbox {
    width: 40rpx;
    height: 40rpx;
    border: 2rpx solid #ddd;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;

    &.checked {
      background: #4CAF50;
      border-color: #4CAF50;
    }
  }
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80rpx 20rpx;

  .empty-image {
    width: 160rpx;
    height: 160rpx;
    margin-bottom: 20rpx;
  }

  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 30rpx;
    display: block;
  }

  .empty-action {
    display: inline-flex;
    align-items: center;
    background: #e6f7ff;
    color: #1890ff;
    padding: 16rpx 32rpx;
    border-radius: 30rpx;
    font-size: 26rpx;

    .empty-action-text {
      margin-left: 8rpx;
    }
  }
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 20rpx;

  .loading-text {
    font-size: 28rpx;
    color: #666;
    margin-top: 20rpx;
  }
}
</style>